package com.innovation.ic.sc.base.service.sc.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.innovation.ic.b1b.framework.util.DateUtils;
import com.innovation.ic.b1b.framework.util.HttpUtils;
import com.innovation.ic.sc.base.mapper.sc.InventoryMapper;
import com.innovation.ic.sc.base.model.sc.*;
import com.innovation.ic.sc.base.pojo.constant.Constants;
import com.innovation.ic.sc.base.pojo.constant.DyjConstants;
import com.innovation.ic.sc.base.pojo.constant.handler.RabbitMqConstants;
import com.innovation.ic.sc.base.pojo.constant.model.AdvantageConstants;
import com.innovation.ic.sc.base.pojo.constant.model.AdvantageModelConstants;
import com.innovation.ic.sc.base.pojo.constant.model.InventoryConstants;
import com.innovation.ic.sc.base.pojo.constant.model.LadderPriceConstants;
import com.innovation.ic.sc.base.pojo.enums.*;
import com.innovation.ic.sc.base.pojo.variable.AuthenticationUser;
import com.innovation.ic.sc.base.pojo.variable.ServiceResult;
import com.innovation.ic.sc.base.pojo.variable.SpecialsScTopViewAddPojo;
import com.innovation.ic.sc.base.pojo.variable.inventory.*;
import com.innovation.ic.sc.base.pojo.variable.ladderPrice.*;
import com.innovation.ic.sc.base.pojo.variable.product.ProductInfoPojo;
import com.innovation.ic.sc.base.service.ServiceHelper;
import com.innovation.ic.sc.base.service.sc.InventoryService;
import com.innovation.ic.sc.base.vo.BrandsPageVo;
import com.innovation.ic.sc.base.vo.inventory.*;
import com.innovation.ic.sc.base.vo.ladderPrice.LadderPriceVo;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @desc   Inventory的具体实现类
 * @author linuo
 * @time   2022年8月23日09:47:27
 */
@Service
//@Transactional
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {
    private static final Logger log = LoggerFactory.getLogger(InventoryServiceImpl.class);

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 根据品牌、型号、供应商id查询库存中的数据
     * @param brand 品牌
     * @param partNumber 型号
     * @param enterpriseId 供应商id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<Inventory>> selectListByPartNumberBrandEpId(String brand, String partNumber, String enterpriseId) {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(InventoryConstants.BRAND_FIELD, brand);
        if(!Strings.isNullOrEmpty(partNumber)){
            queryWrapper.eq(InventoryConstants.PART_NUMBER_FIELD, partNumber);
        }
        queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, enterpriseId);

        ServiceResult<List<Inventory>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(serviceHelper.getInventoryMapper().selectList(queryWrapper));
        return serviceResult;
    }

    /**
     * 处理库存数据删除队列数据
     * @param id 库存id
     * @return 返回处理结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<Boolean> handleInventoryDeleteQueueData(Integer id) {
        Boolean result = Boolean.FALSE;
        String message = ServiceResult.OPERATE_FAIL;

        int i = serviceHelper.getInventoryMapper().deleteById(id);
        if(i > 0){
            result = Boolean.TRUE;
            message = ServiceResult.OPERATE_SUCCESS;
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 插入库存数据
     * @param inventory 库存数据
     */
    @Override
    public int insertInventoryData(Inventory inventory) {
        return serviceHelper.getInventoryMapper().insert(inventory);
    }

    /**
     * 初始化库存数据
     */
    @Override
    public void initInventoryData() {
        // 删除redis中的优势型号数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.INVENTORY_DATA.getCode() + "*");
        if(deleteResult){
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.INVENTORY_DATA.getCode());
        }

        // 获取优势型号表的所有数据
        List<Inventory> inventories = serviceHelper.getInventoryMapper().selectList(null);
        if(inventories != null && inventories.size() > 0){
            for(Inventory inventory : inventories){
                String key = RedisKeyPrefixEnum.INVENTORY_DATA.getCode() + "_" + inventory.getId();
                String apiResultJson = JSONObject.toJSONString(inventory, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue);
                serviceHelper.getRedisManager().set(key, apiResultJson);
            }
        }
        log.info("导入[{}]开头的数据成功", RedisKeyPrefixEnum.INVENTORY_DATA.getCode());
    }

    /**
     * 将Inventory列表查询的结果数据导入到redis
     */
    @Override
    public void importQueryResultToRedis() {
        // 删除redis中的优势型号数据
        Boolean deleteResult = serviceHelper.getRedisManager().delRedisDataByKeyPrefix(RedisKeyPrefixEnum.INVENTORY_QUERY.getCode() + "*");
        if(deleteResult){
            log.info("删除[{}]开头的数据成功", RedisKeyPrefixEnum.INVENTORY_QUERY.getCode());
        }

        // 获取根据状态、库存所在地、价格类型、阶梯价格id、供应商id获取数据库中包含的所有情况
        List<InventoryAllSituationPojo> allSituation = serviceHelper.getInventoryMapper().selectAllSituationByParam();

        // 查询全部供应商id
        List<String> list = serviceHelper.getInventoryMapper().getEnterpriseIds();

        // 添加特殊情况数据
        addSpecialInventoryAllSituationPojoData(allSituation, list);

        if(allSituation != null && allSituation.size() > 0){
            for(InventoryAllSituationPojo inventoryAllSituationPojo : allSituation){
                String status = null;
                if(inventoryAllSituationPojo.getStatus() != null){
                    status = inventoryAllSituationPojo.getStatus().toString();
                }

                String inventoryHome = null;
                if(inventoryAllSituationPojo.getInventoryHome() != null){
                    inventoryHome = inventoryAllSituationPojo.getInventoryHome().toString();
                }

                // 根据参数获取库存在redis中的key
                String key = getInventoryRedisKeyByParam(status, inventoryHome, inventoryAllSituationPojo.getUnitPriceType(),
                        inventoryAllSituationPojo.getLadderPriceId(), inventoryAllSituationPojo.getEnterpriseId());

                // 根据条件查询数据
                List<InventoryBatchQueryPojo> data = serviceHelper.getInventoryMapper().queryDataByParam(inventoryAllSituationPojo);

                // 判断是否为优势型号和优势品牌，补充字段
                judgeIfAdvantageBrandModel(data);

                // 将库存列表查询结果数据添加到redis中
                addInventoryQueryResultDataToRedis(key, data);
            }
        }

        log.info("导入[{}]开头的数据成功", RedisKeyPrefixEnum.INVENTORY_QUERY.getCode());
    }

    /**
     * 根据参数插入库存的redis数据
     * @param status 状态
     * @param inventoryHome 库存所在地
     * @param unitPriceType 价格类型
     * @param ladderPriceId 阶梯价格id
     * @param enterpriseId 供应商id
     */
    @Override
    public void updateInventoryRedisDataByParam(Integer status, Integer inventoryHome, Integer unitPriceType, Integer ladderPriceId, String enterpriseId) {
        String statusStr = null;
        if(status != null){
            statusStr = status.toString();
        }

        String inventoryHomeStr = null;
        if(inventoryHome != null){
            inventoryHomeStr = inventoryHome.toString();
        }

        // 根据参数获取库存在redis中的key
        String key = getInventoryRedisKeyByParam(statusStr, inventoryHomeStr, unitPriceType, ladderPriceId, enterpriseId);

        // 删除redis中的数据
        serviceHelper.getRedisManager().del(key);

        // 根据条件查询数据
        InventoryAllSituationPojo inventoryAllSituationPojo = new InventoryAllSituationPojo();
        inventoryAllSituationPojo.setStatus(status);
        inventoryAllSituationPojo.setInventoryHome(inventoryHome);
        inventoryAllSituationPojo.setUnitPriceType(unitPriceType);
        inventoryAllSituationPojo.setLadderPriceId(ladderPriceId);
        inventoryAllSituationPojo.setEnterpriseId(enterpriseId);
        List<InventoryBatchQueryPojo> data = serviceHelper.getInventoryMapper().queryDataByParam(inventoryAllSituationPojo);

        // 判断是否为优势型号，补充字段
        judgeIfAdvantageBrandModel(data);

        // 将库存列表查询结果数据添加到redis中
        addInventoryQueryResultDataToRedis(key, data);
    }

    /**
     * 查询当前供应商全部匹配上标准库的数据id集合
     * @param epId 供应商id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<Integer>> getMatchStandardLibraryInventoryIds(String epId) {
        List<Integer> result = serviceHelper.getInventoryMapper().getMatchStandardLibraryInventoryIds(epId);

        ServiceResult<List<Integer>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 校验dataList中的标准匹配型号和标准匹配品牌是否被已有数据使用
     * @param dataList 库存确认匹配结果集合
     * @param epId     供应商id
     * @return 返回判断结果
     */
    @Override
    public ServiceResult<List<Integer>> judgeStandardDataIfHaveUsed(List<InventoryMatchResultVo> dataList, String epId) {
        List<Integer> result = new ArrayList<>();

        // 判断dataList数据是否有重复的品牌和型号
        for (int i = 0; i < dataList.size(); i++) {
            InventoryMatchResultVo inventoryMatchResultVo = dataList.get(i);
            for (int j = i + 1; j < dataList.size(); j++) {
                InventoryMatchResultVo inventoryMatchResultVo1 = dataList.get(j);
                if(inventoryMatchResultVo.getBzkBrand().equals(inventoryMatchResultVo1.getBzkBrand()) && inventoryMatchResultVo.getBzkPartNumber().equals(inventoryMatchResultVo1.getBzkPartNumber())){
                    result.add(inventoryMatchResultVo.getId());
                    result.add(inventoryMatchResultVo1.getId());
                }
            }
        }

        // 判断dataList中的品牌和型号是否有历史数据使用
        for(InventoryMatchResultVo inventoryMatchResultVo : dataList){
            Integer count = serviceHelper.getInventoryMapper().selectUseStandardDataCount(inventoryMatchResultVo.getBzkBrand(), inventoryMatchResultVo.getBzkPartNumber(), epId);
            if(count > 0){
                result.add(inventoryMatchResultVo.getId());
            }
        }

        // list去重
        if(result.size() > 1){
            result = new ArrayList<>(new TreeSet<>(result));
        }

        ServiceResult<List<Integer>> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 确认标准匹配结果
     * @param inventoryConfirmMatchResultVo 库存确认匹配结果的Vo类
     * @return 返回处理结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<Boolean> confirmStandardMatchResult(InventoryConfirmMatchResultVo inventoryConfirmMatchResultVo) throws IOException {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.OPERATE_FAIL;

        List<InventoryMatchResultVo> dataList = inventoryConfirmMatchResultVo.getDataList();
        if(dataList != null && dataList.size() > 0){
            for(InventoryMatchResultVo inventoryMatchResultVo : dataList) {
                Inventory inventory = new Inventory();
//                inventory.setBzkMatchStatus(InventoryMatchStatusEnum.MATCHED.getType());
//                inventory.setBzkPartNumber(inventoryMatchResultVo.getBzkPartNumber());
//                inventory.setBzkBrand(inventoryMatchResultVo.getBzkBrand());
                inventory.setModifyDate(new Date(System.currentTimeMillis()));

                UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq(Constants.ID, inventoryMatchResultVo.getId());

                int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
                if(update > 0){
                    result = Boolean.TRUE;
                    message = ServiceResult.OPERATE_SUCCESS;

                    // 推送库存新增、修改数据的mq消息到erp
                    sendInventoryAddEditDataMqMsgToErp(inventoryMatchResultVo.getId());
                }
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 库存信息编辑更新
     * @param inventoryEditVo 库存信息编辑更新接口的Vo类
     * @return 返回更新结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<Boolean> edit(InventoryEditVo inventoryEditVo) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        Boolean result = Boolean.FALSE;
        String message = null;

        try {
            // 单价四舍五入为6位小数
            BigDecimal unitPrice = inventoryEditVo.getUnitPrice();
            if(unitPrice != null){
                unitPrice = unitPrice.setScale(6, BigDecimal.ROUND_HALF_UP);
                inventoryEditVo.setUnitPrice(unitPrice);
            }

            Inventory inventory = new Inventory();
            BeanUtils.copyProperties(inventoryEditVo, inventory);
            inventory.setId(null);

            if(inventory.getUnitPriceType() != null && inventory.getUnitPriceType().intValue() == UnitPriceTypeEnum.SINGLE_PRICE.getCode().intValue()){
                // 如果价格类型修改为了单一价格，需要将阶梯价格id字段置为空
                int i = serviceHelper.getInventoryMapper().setLadderPriceIdNullById(inventoryEditVo.getId());
                if(i > 0){
                    inventory.setLadderPriceId(null);
                }
            }

            UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq(Constants.ID, inventoryEditVo.getId());
            int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
//            int update = serviceHelper.getInventoryMapper().updateInventory(inventoryEditVo.getId(), inventory.getBatch());
            if(update > 0){
                message = ServiceResult.UPDATE_SUCCESS;
                result = Boolean.TRUE;
                log.info("库存信息数据更新成功,库存id:[{}]", inventoryEditVo.getId());

                // 推送库存新增、修改数据的mq消息到erp
                sendInventoryAddEditDataMqMsgToErp(inventoryEditVo.getId());
            }
        }catch (Exception e){
            log.info("库存信息编辑更新出现问题,原因:", e);
            message = ServiceResult.UPDATE_FAIL;
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    @Override
    public ServiceResult<PageInfo<Inventory>> findBrand(BrandsPageVo brandsPageVo) {
        ServiceResult<PageInfo<Inventory>> serviceResult = new ServiceResult<>();
        PageHelper.startPage(brandsPageVo.getPageNo(), brandsPageVo.getPageSize());
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(new PageInfo<>(this.baseMapper.findBrand(brandsPageVo)));
        return serviceResult;

    }

    /**
     * 库存新增
     * @param inventoryAddVo 库存新增接口的Vo类
     * @param authenticationUser 用户信息
     * @return 返回新增结果
     */
    @Override
    public ServiceResult<InventoryAddRespPojo> add(InventoryAddVo inventoryAddVo, AuthenticationUser authenticationUser) throws IOException, InterruptedException {
        ServiceResult<InventoryAddRespPojo> serviceResult = new ServiceResult<>();

        boolean result = Boolean.FALSE;
        String message = null;

        InventoryAddRespPojo inventoryAddRespPojo = new InventoryAddRespPojo();

        try {
            // 上传成功的数据数量
            int successCount = 0;

            // 库存数据
            List<InventoryAddParamVo> inventoryList = inventoryAddVo.getInventoryList();
            for (InventoryAddParamVo inventoryAddParamVo : inventoryList) {
                // 插入库存数据
                Map<String, Object> map = insertInventory(inventoryAddParamVo, authenticationUser);

                // 推送库存新增、修改数据的mq消息到erp
                if(map != null && map.get(Constants.ID) != null){
                    result = Boolean.TRUE;
                    message = ServiceResult.INSERT_SUCCESS;
                    sendInventoryAddEditDataMqMsgToErp((Integer) map.get(Constants.ID));
                    successCount++;
                }
            }

            // 上传库存的全部数据数量
            inventoryAddRespPojo.setAllCount(inventoryList.size());

            // 上传成功的数据数量
            inventoryAddRespPojo.setSuccessCount(successCount);
        }catch (Exception e){
            log.warn("库存新增出现问题,原因:", e);
            message = "保存失败，请重试";
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(inventoryAddRespPojo);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 库存批量导入
     * @param inventoryBatchAddVo 库存批量导入接口的Vo类
     * @param authenticationUser  用户信息
     * @return 返回导入结果
     */
    @Override
    public ServiceResult<InventoryAddRespPojo> batchAdd(InventoryBatchAddVo inventoryBatchAddVo, AuthenticationUser authenticationUser) throws IOException {
        ServiceResult<InventoryAddRespPojo> serviceResult = new ServiceResult<>();

        InventoryAddRespPojo result = null;
        String message;

        try {
            // 覆盖方式需要删除历史库存数据及阶梯价格配置数据
            if(ImportTypeEnum.COVER.getCode().intValue() == inventoryBatchAddVo.getImportType().intValue()){
                log.info("用户正在使用覆盖方式删除数据,供应商id:[{}]的历史数据均会被清除", authenticationUser.getEpId());

                // 删除历史库存数据
                deleteHistoryInventoryData(authenticationUser.getEpId());

                // 删除阶梯价格配置数据
                // deleteHistoryLadderPriceData(authenticationUser.getEpId());
            }

            // 插入新的库存数据
            result = batchAddInsertInventory(inventoryBatchAddVo, authenticationUser);
            message = ServiceResult.INSERT_SUCCESS;
        }catch (Exception e){
            log.error("库存批量导入出现问题,原因:", e);
            message = "保存失败，请重试";
        }

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 优势型号状态变更
     * @param inventoryUpdateAdvantageStatusVo 优势型号状态变更接口的Vo类
     * @param authenticationUser               用户信息
     * @return 返回操作结果
     */
    @SneakyThrows
    @Override
    public ServiceResult<Boolean> updateAdvantageStatus(InventoryUpdateAdvantageStatusVo inventoryUpdateAdvantageStatusVo, AuthenticationUser authenticationUser) throws Exception {
        // 处理符合条件的所有数据
        if(inventoryUpdateAdvantageStatusVo.getIsAll() != null && inventoryUpdateAdvantageStatusVo.getIsAll()) {
            // 根据参数查询需要删除的id集合
            List<Integer> ids = getMatchConditionIdList(inventoryUpdateAdvantageStatusVo.getBrand(), inventoryUpdateAdvantageStatusVo.getPartNumber(),
                    inventoryUpdateAdvantageStatusVo.getStartDate(), inventoryUpdateAdvantageStatusVo.getEndDate(), inventoryUpdateAdvantageStatusVo.getStatus(),
                    inventoryUpdateAdvantageStatusVo.getInventoryHome(), inventoryUpdateAdvantageStatusVo.getUnitPriceType(),
                    inventoryUpdateAdvantageStatusVo.getLadderPriceId(), authenticationUser.getEpId());
            if(ids != null && ids.size() > 0){
                for(Integer id : ids){
                    // 优势型号状态变更，推送mq消息
                    updateAdvantageStatusSendMsg(id, inventoryUpdateAdvantageStatusVo);
                }
            }
        }else{
            List<Integer> idList = inventoryUpdateAdvantageStatusVo.getIdList();
            for(Integer id : idList){
                // 优势型号状态变更，推送mq消息
                updateAdvantageStatusSendMsg(id, inventoryUpdateAdvantageStatusVo);
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
        return serviceResult;
    }

    /**
     * 优势型号状态变更，推送mq消息
     * @param id 主键id
     * @param inventoryUpdateAdvantageStatusVo 优势型号状态变更接口的Vo类
     * @return 返回更新结果
     */
    private boolean updateAdvantageStatusSendMsg(Integer id, InventoryUpdateAdvantageStatusVo inventoryUpdateAdvantageStatusVo) throws Exception {
        boolean result = Boolean.FALSE;

        // 操作类型(0:取消优势型号、1:设为优势型号)
        Integer operateType = inventoryUpdateAdvantageStatusVo.getOperateType();

        Inventory historyData = serviceHelper.getInventoryMapper().selectById(id);
        if(historyData == null || (historyData.getAdvantageStatus() != null && operateType.intValue() == historyData.getAdvantageStatus().intValue())){
            log.info("库存id为[{}]的数据状态与需要操作的状态一致,无需再次操作", id);
            return result;
        }

        Inventory inventory = new Inventory();
        if(operateType.intValue() == AdvantageStatusEnum.INVALID.getScStatusCode().intValue()){
            inventory.setAdvantageStatus(AdvantageStatusEnum.INVALID.getScStatusCode());
        }else{
            inventory.setAuditStatus(AuditStatusEnum.PENDING.getScStatusCode());
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        // 有效日期开始
        if(!Strings.isNullOrEmpty(inventoryUpdateAdvantageStatusVo.getValidityDateStart())){
            inventory.setValidityDateStart(sdf.parse(inventoryUpdateAdvantageStatusVo.getValidityDateStart()));
        }

        // 有效日期结束
        if(!Strings.isNullOrEmpty(inventoryUpdateAdvantageStatusVo.getValidityDateEnd())){
            inventory.setValidityDateEnd(sdf.parse(inventoryUpdateAdvantageStatusVo.getValidityDateEnd()));
        }

        // 备注
        if(!Strings.isNullOrEmpty(inventoryUpdateAdvantageStatusVo.getRemark())){
            inventory.setRemark(inventoryUpdateAdvantageStatusVo.getRemark());
        }

        UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(InventoryConstants.ID_FIELD, id);
        int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
        if(update > 0){
            // 取消优势型号需要推送消息到mq
            if(operateType.intValue() == AdvantageStatusEnum.INVALID.getScStatusCode().intValue()){
                sendInventoryAddEditDataMqMsgToErp(id);

                Inventory inventory1 = serviceHelper.getInventoryMapper().selectById(id);
                if(inventory1 != null){
                    // 取消优势型号推送mq消息
                    cancleAdvantageModelSendMqMsg(inventory1.getErpId());
                }
            }else{
                // 推送消息到erp进行审核
                sendMqMsgToErpAddAdvantageModel(id);
            }
            result = Boolean.TRUE;
        }
        return result;
    }

    /**
     * 取消优势型号推送mq消息
     * @param erpId erpId
     */
    private void cancleAdvantageModelSendMqMsg(String erpId) throws IOException {
        JSONObject json = new JSONObject();
        json.put(AdvantageConstants.ID, erpId);

        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_CLOSE_QUEUE);

        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_CLOSE_QUEUE, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_CLOSE_QUEUE, null, result.toString().getBytes());

    }

    /**
     * 推送mq消息到erp新增优势型号信息
     * @param id 优势型号主键id
     */
    private void sendMqMsgToErpAddAdvantageModel(Integer id) throws IOException {
        if(id != null){
            Inventory inventory = serviceHelper.getInventoryMapper().selectById(id);
            if(inventory != null){
                SpecialsScTopViewAddPojo specialsScTopViewAddPojo = new SpecialsScTopViewAddPojo();
                specialsScTopViewAddPojo.setEnterpriseID(inventory.getEnterpriseId());
                specialsScTopViewAddPojo.setPartNumber(inventory.getPartNumber());
                specialsScTopViewAddPojo.setBrand(inventory.getBrand());
                specialsScTopViewAddPojo.setStartDate(inventory.getValidityDateStart());
                specialsScTopViewAddPojo.setEndDate(inventory.getValidityDateEnd());
                specialsScTopViewAddPojo.setCreator(inventory.getCreateUser());
                specialsScTopViewAddPojo.setSummary(inventory.getRemark());
                JSONObject json = (JSONObject) JSONObject.toJSON(specialsScTopViewAddPojo);

                // 包装发送到rabbitmq的消息内容
                JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_ADD_QUEUE);

                log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_ADD_QUEUE, result.toString());
                serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_TO_ERP_CRM_QUEUE_NAME, RabbitMqConstants.SC_ERP_ADD_QUEUE, null, result.toString().getBytes());
            }
        }
    }

    /**
     * 库存上架/下架
     * @param inventoryStatusUpdateReqVo 库存上架/下架接口的Vo类
     * @param authenticationUser 登录用户
     * @return 返回更新结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<List<Map<String, String>>> updateStatus(InventoryStatusUpdateReqVo inventoryStatusUpdateReqVo, AuthenticationUser authenticationUser) throws IOException {
        ServiceResult<List<Map<String, String>>> serviceResult = new ServiceResult<>();

        List<Map<String, String>> list = new ArrayList<>();

        // 处理符合条件的所有数据
        if(inventoryStatusUpdateReqVo.getIsAll() != null && inventoryStatusUpdateReqVo.getIsAll()) {
            // 根据参数查询需要删除的id集合
            List<Integer> ids = getMatchConditionIdList(inventoryStatusUpdateReqVo.getBrand(), inventoryStatusUpdateReqVo.getPartNumber(), inventoryStatusUpdateReqVo.getStartDate(),
                    inventoryStatusUpdateReqVo.getEndDate(), inventoryStatusUpdateReqVo.getStatus(), inventoryStatusUpdateReqVo.getInventoryHome(),
                    inventoryStatusUpdateReqVo.getUnitPriceType(), inventoryStatusUpdateReqVo.getLadderPriceId(), authenticationUser.getEpId());
            if(ids != null && ids.size() > 0){
                for(Integer id : ids){
                    // 更新库存状态，推送mq消息
                    Integer integer = updateInventoryStatusSendMsg(id, inventoryStatusUpdateReqVo.getUpdateStatus());
                    if(integer > 0){
                        list.add(getModelMapByInventoryId(id));
                    }
                }
            }
        }else{
            for(Integer id : inventoryStatusUpdateReqVo.getIdList()){
                // 更新库存状态，推送mq消息
                Integer integer = updateInventoryStatusSendMsg(id, inventoryStatusUpdateReqVo.getUpdateStatus());
                if(integer > 0){
                    list.add(getModelMapByInventoryId(id));
                }
            }
        }

        /*for(Integer id : inventoryStatusUpdateReqVo.getIdList()){
            // 更新库存状态，推送mq消息
            Integer integer = updateInventoryStatusSendMsg(id, inventoryStatusUpdateReqVo.getUpdateStatus());
            if(integer > 0){
                list.add(getModelMapByInventoryId(id));
            }
        }*/

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(list);
        return serviceResult;
    }

    /**
     * 库存信息删除
     * @param inventoryDeleteVo 删除库存数据的Vo类
     * @param authenticationUser 登录用户
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delete(InventoryDeleteVo inventoryDeleteVo, AuthenticationUser authenticationUser) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        boolean result = Boolean.FALSE;

        int count = 0;

        // 全部删除
        if(inventoryDeleteVo.getIsAll() != null && inventoryDeleteVo.getIsAll()){
            // 根据参数查询需要删除的id集合
            List<Integer> ids = getMatchConditionIdList(inventoryDeleteVo.getBrand(), inventoryDeleteVo.getPartNumber(), inventoryDeleteVo.getStartDate(), inventoryDeleteVo.getEndDate(),
                    inventoryDeleteVo.getStatus(), inventoryDeleteVo.getInventoryHome(), inventoryDeleteVo.getUnitPriceType(), inventoryDeleteVo.getLadderPriceId(), authenticationUser.getEpId());
            if(ids != null && ids.size() > 0){
                for(Integer id : ids){
                    int i = deleteInventorySendMqMsg(id);
                    if(i > 0){
                        count++;
                        result = Boolean.TRUE;
                    }
                }
            }
        }else{
            for(Integer id : inventoryDeleteVo.getIdList()){
                int i = deleteInventorySendMqMsg(id);
                if(i > 0){
                    count++;
                    result = Boolean.TRUE;
                }
            }
        }

        /*for(Integer id : inventoryDeleteVo.getIdList()){
            int i = deleteInventorySendMqMsg(id);
            if(i > 0){
                count++;
                result = Boolean.TRUE;
            }
        }*/

        if(count == 0){
            log.info("id={}的库存数据已删除成功,本次删除无数据操作", inventoryDeleteVo.getIdList());
            result = Boolean.TRUE;
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 库存时间更新
     * @param inventoryUpdateDateVo 库存时间更新接口的Vo类
     * @param authenticationUser 登录用户
     * @return 返回更新结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<Boolean> updateInventoryDate(InventoryUpdateDateVo inventoryUpdateDateVo, AuthenticationUser authenticationUser) throws IOException {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        boolean result = Boolean.FALSE;

        // 全部更新
        if(inventoryUpdateDateVo.getIsAll() != null && inventoryUpdateDateVo.getIsAll()) {
            // 获取符合条件的库存id集合
            List<Integer> ids = getMatchConditionIdList(inventoryUpdateDateVo.getBrand(), inventoryUpdateDateVo.getPartNumber(), inventoryUpdateDateVo.getStartDate(), inventoryUpdateDateVo.getEndDate(),
                    inventoryUpdateDateVo.getStatus(), inventoryUpdateDateVo.getInventoryHome(), inventoryUpdateDateVo.getUnitPriceType(), inventoryUpdateDateVo.getLadderPriceId(), authenticationUser.getEpId());
            if (ids != null && ids.size() > 0) {
                UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
                updateWrapper.in(Constants.ID_FIELD, ids);

                Inventory inventory = new Inventory();
                inventory.setModifyDate(new Date(System.currentTimeMillis()));
                int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
                if(update > 0){
                    log.info("更新库存时间成功");
                    result = Boolean.TRUE;

                    // 推送库存新增、修改数据的mq消息到erp
                    for(Integer id : ids){
                        sendInventoryAddEditDataMqMsgToErp(id);
                    }
                }
            }
        }else{
            UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in(Constants.ID_FIELD, inventoryUpdateDateVo.getIdList());

            Inventory inventory = new Inventory();
            inventory.setModifyDate(new Date(System.currentTimeMillis()));
            int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
            if(update > 0){
                log.info("更新库存时间成功");
                result = Boolean.TRUE;

                // 推送库存新增、修改数据的mq消息到erp
                for(Integer id : inventoryUpdateDateVo.getIdList()){
                    sendInventoryAddEditDataMqMsgToErp(id);
                }
            }
        }

        serviceResult.setSuccess(result);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 库存信息列表查询
     * @param inventoryQueryVo 库存信息列表查询接口的Vo类
     * @param epId 供应商id
     * @return 返回 库存信息列表信息
     */
    @Override
    public ServiceResult<JSONObject> query(InventoryQueryVo inventoryQueryVo, String epId) throws ParseException {
        ServiceResult<JSONObject> serviceResult = new ServiceResult<>();

        /*List<InventoryBatchQueryRespPojo> result = new ArrayList<>();

        // 库存数据总条数
        int count = 0;

        //进行分页查询
        Integer pageNo = inventoryQueryVo.getPageNo();
        Integer pageSize = inventoryQueryVo.getPageSize();
        if(pageNo != null && pageSize != null){
            pageNo = pageSize * (pageNo - 1) + 1;
        }

        *//* 根据条件获取库存数据 *//*
        Set<String> inventorySet = getInventoryDataListFromRedis(inventoryQueryVo.getStatus(), inventoryQueryVo.getInventoryHome(),
                inventoryQueryVo.getUnitPriceType(), inventoryQueryVo.getLadderPriceId(), epId);
        if(inventorySet != null && inventorySet.size() > 0){
            // 数据序列化
            List<InventoryBatchQueryPojo> redisList = serviceHelper.getModelHandler().toInventoryList(inventorySet);

            // 根据请求参数筛选数据
            List<InventoryBatchQueryPojo> dataList = screenRedisList(redisList, inventoryQueryVo);
            count = dataList.size();

            // 如果查询的开始计数位置大于数据的条数，则将数据条数赋值为0，查询数据为空
            if(pageNo > count){
                count = 0;
            }

            // 组装库存信息列表查询数据
            if(count > 0){
                // 计数
                int num = 0;

                // 获取的数据数量计数
                int dataCount = 0;

                for(InventoryBatchQueryPojo inventory : dataList){
                    num++;
                    // 未达到获取数据的计数位置时不处理
                    if(pageNo > num){
                        continue;
                    }

                    InventoryBatchQueryRespPojo inventoryBatchQueryRespPojo = new InventoryBatchQueryRespPojo();
                    BeanUtils.copyProperties(inventory, inventoryBatchQueryRespPojo);
                    Integer unitPriceType = inventoryBatchQueryRespPojo.getUnitPriceType();

                    // 起订量集合
                    List<Integer> mqList = new ArrayList<>();

                    // 单价集合
                    List<String> unitPriceList = new ArrayList<>();

                    // 单一价格
                    if(unitPriceType.intValue() == UnitPriceTypeEnum.SINGLE_PRICE.getCode().intValue()){
                        inventoryBatchQueryRespPojo.setMq(inventory.getMoq());
                        mqList.add(inventory.getMoq());
                        if(inventory.getUnitPrice() != null){
                            BigDecimal unitPrice = (BigDecimal) inventory.getUnitPrice();
                            unitPrice = unitPrice.setScale(6, BigDecimal.ROUND_HALF_UP);
                            unitPriceList.add(unitPrice.toString());
                            inventoryBatchQueryRespPojo.setUnitPrice(unitPrice.toString());
                        }
                        inventoryBatchQueryRespPojo.setMqList(mqList);
                        inventoryBatchQueryRespPojo.setUnitPriceList(unitPriceList);
                    }

                    // 阶梯价格
                    if(unitPriceType.intValue() == UnitPriceTypeEnum.LADDER_PRICE.getCode().intValue()){
                        // 根据单价获取阶梯价格配置
                        Map<String, Object> ladderPriceConfigData = getLadderPriceConfigData(inventory.getLadderPriceId(), (BigDecimal) inventory.getUnitPrice());
                        inventoryBatchQueryRespPojo.setMqList((List<Integer>) ladderPriceConfigData.get("mqList"));
                        inventoryBatchQueryRespPojo.setUnitPriceList((List<String>) ladderPriceConfigData.get("unitPriceList"));
                        inventoryBatchQueryRespPojo.setUnitPriceConfig((List<LadderPriceConfigPojo>) ladderPriceConfigData.get("unitPriceConfig"));
                    }
                    result.add(inventoryBatchQueryRespPojo);
                    dataCount++;

                    // 若获取到了需要的数量，则终止处理
                    if(dataCount == pageSize){
                        break;
                    }
                }
            }
        }

        // 进行降序展示
        result.sort(Comparator.comparing(InventoryBatchQueryRespPojo::getId).reversed());
        result.sort(Comparator.comparing(InventoryBatchQueryRespPojo::getModifyDate).reversed());
        result.sort(Comparator.comparing(InventoryBatchQueryRespPojo::getStatus).reversed());

        // 组装返回数据
        JSONObject json = new JSONObject();
        json.put(Constants.COUNT, count);
        json.put(Constants.DATA_FIELD, result);*/

        // 进行分页查询
        Integer pageNo = inventoryQueryVo.getPageNo();
        Integer pageSize = inventoryQueryVo.getPageSize();
        if(pageNo != null && pageSize != null){
            inventoryQueryVo.setPageNo(pageSize * (pageNo - 1));
        }
        List<InventoryBatchQueryPojo> list = serviceHelper.getInventoryMapper().query(inventoryQueryVo, epId);

        // 组装库存信息列表查询数据
        List<InventoryBatchQueryRespPojo> result = new ArrayList<>();
        if(list != null && list.size() > 0){
            for(InventoryBatchQueryPojo inventory : list){
                InventoryBatchQueryRespPojo inventoryBatchQueryRespPojo = new InventoryBatchQueryRespPojo();
                BeanUtils.copyProperties(inventory, inventoryBatchQueryRespPojo);
                Integer unitPriceType = inventoryBatchQueryRespPojo.getUnitPriceType();

                // 起订量集合
                List<Integer> mqList = new ArrayList<>();

                // 单价集合
                List<String> unitPriceList = new ArrayList<>();

                // 单一价格
                if(unitPriceType.intValue() == UnitPriceTypeEnum.SINGLE_PRICE.getCode().intValue()){
                    inventoryBatchQueryRespPojo.setMq(inventory.getMoq());
                    mqList.add(inventory.getMoq());
                    if(inventory.getUnitPrice() != null){
                        BigDecimal unitPrice = (BigDecimal) inventory.getUnitPrice();
                        unitPrice = unitPrice.setScale(6, BigDecimal.ROUND_HALF_UP);
                        unitPriceList.add(unitPrice.toString());
                        inventoryBatchQueryRespPojo.setUnitPrice(unitPrice.toString());
                    }
                    inventoryBatchQueryRespPojo.setMqList(mqList);
                    inventoryBatchQueryRespPojo.setUnitPriceList(unitPriceList);
                }

                // 品牌是否优势
                if(inventoryBatchQueryRespPojo.getIfAdvantageModel() != null && inventoryBatchQueryRespPojo.getIfAdvantageModel() > 1){
                    inventoryBatchQueryRespPojo.setIfAdvantageModel(AdvantageStatusEnum.EFFECTIVE.getScStatusCode());
                }

                // 阶梯价格
                if(unitPriceType.intValue() == UnitPriceTypeEnum.LADDER_PRICE.getCode().intValue()){
                    // 根据单价获取阶梯价格配置
                    Map<String, Object> ladderPriceConfigData = getLadderPriceConfigData(inventory.getLadderPriceId(), (BigDecimal) inventory.getUnitPrice());
                    inventoryBatchQueryRespPojo.setMqList((List<Integer>) ladderPriceConfigData.get("mqList"));
                    inventoryBatchQueryRespPojo.setUnitPriceList((List<String>) ladderPriceConfigData.get("unitPriceList"));
                    inventoryBatchQueryRespPojo.setUnitPriceConfig((List<LadderPriceConfigPojo>) ladderPriceConfigData.get("unitPriceConfig"));
                }
                result.add(inventoryBatchQueryRespPojo);
            }
        }

        //进行降序展示
        result.sort(Comparator.comparing(InventoryBatchQueryRespPojo::getModifyDate).reversed());

        // 获取库存数据总条数
        Long count = serviceHelper.getInventoryMapper().queryCount(inventoryQueryVo, epId);

        // 组装返回数据
        JSONObject json = new JSONObject();
        json.put(Constants.COUNT, count);
        json.put(Constants.DATA_FIELD, result);

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(json);
        return serviceResult;
    }

    /**
     * 根据单价获取阶梯价格配置
     * @param ladderPriceId 阶梯价格id
     * @param price 价格
     * @return 返回结果
     */
    private Map<String, Object> getLadderPriceConfigData(Integer ladderPriceId, BigDecimal price){
        Map<String, Object> result = new HashMap<>();

        // 起订量集合
        List<Integer> mqList = new ArrayList<>();

        // 单价集合
        List<String> unitPriceList = new ArrayList<>();

        // 阶梯价格配置
        List<LadderPriceConfigPojo> unitPriceConfig = new ArrayList<>();

        if(ladderPriceId != null && price != null){
            // 根据阶梯价格id获取阶梯价格配置集合
            List<LadderPriceConfig> ladderPriceConfigList = getLadderPriceConfigListByLadderPriceId(ladderPriceId, price);
            if(ladderPriceConfigList != null && ladderPriceConfigList.size() > 0){
                for(LadderPriceConfig ladderPriceConfig : ladderPriceConfigList){
                    mqList.add(ladderPriceConfig.getMq());

                    // 根据降比计算降比后的价格
                    BigDecimal unitPrice = serviceHelper.getPriceCalculateHandler().calculateUnitPriceByLower(price, ladderPriceConfig.getLower());
                    unitPriceList.add(unitPrice.toString());

                    LadderPriceConfigPojo ladderPriceConfigPojo = new LadderPriceConfigPojo();
                    ladderPriceConfigPojo.setMq(ladderPriceConfig.getMq());
                    ladderPriceConfigPojo.setUnitPrice(unitPrice.toString());
                    unitPriceConfig.add(ladderPriceConfigPojo);
                }
            }
        }

        result.put("mqList", mqList);
        result.put("unitPriceList", unitPriceList);
        result.put("unitPriceConfig", unitPriceConfig);

        return result;
    }

    /**
     * 库存信息列表批量查询
     * @param inventoryBatchQueryVo 库存信息列表批量查询接口的Vo类
     * @param authenticationUser 登录账户
     * @return 返回 库存信息列表信息
     */
    @Override
    public ServiceResult<List<InventoryGetListRespPojo>> batchQuery(InventoryBatchQueryVo inventoryBatchQueryVo, AuthenticationUser authenticationUser){
        ServiceResult<List<InventoryGetListRespPojo>> serviceResult = new ServiceResult<>();

        List<InventoryGetListRespPojo> result = new ArrayList<>();
        if(inventoryBatchQueryVo.getIsAll() != null && inventoryBatchQueryVo.getIsAll()){
            // 根据参数查询需要查询的id集合
            List<Integer> ids = getMatchConditionIdList(inventoryBatchQueryVo.getBrand(), inventoryBatchQueryVo.getPartNumber(), inventoryBatchQueryVo.getStartDate(),
                    inventoryBatchQueryVo.getEndDate(), inventoryBatchQueryVo.getStatus(), inventoryBatchQueryVo.getInventoryHome(),
                    inventoryBatchQueryVo.getUnitPriceType(), inventoryBatchQueryVo.getLadderPriceId(), authenticationUser.getEpId());
            if(ids != null && ids.size() > 0){
                result = serviceHelper.getInventoryMapper().selectInventoryByIds(ids);
                // 处理库存阶梯价格数据
                result = handleInventoryLadderPriceData(result);
            }
        }else{
            if(inventoryBatchQueryVo.getIdList() != null && inventoryBatchQueryVo.getIdList().size() > 0){
                result = serviceHelper.getInventoryMapper().selectInventoryByIds(inventoryBatchQueryVo.getIdList());
                // 处理库存阶梯价格数据
                result = handleInventoryLadderPriceData(result);
            }
        }

        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 默认阶梯价格配置查询
     * @param epId 供应商id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<List<DefaultLadderPricePojo>> getDefaultLadderPrice(String epId) {
        ServiceResult<List<DefaultLadderPricePojo>> serviceResult = new ServiceResult<>();
        Map<String, Object> param = new HashMap<>();
        param.put(Constants.ENTERPRISE_ID_FIELD, epId);
        List<DefaultLadderPricePojo> result = new ArrayList<>();
        List<DefaultLadderPrice> defaultLadderPrices = serviceHelper.getDefaultLadderPriceMapper().selectByMap(param);
        for (DefaultLadderPrice defaultLadderPrice : defaultLadderPrices) {
            DefaultLadderPricePojo defaultLadderPricePojo = new DefaultLadderPricePojo();
            BeanUtils.copyProperties(defaultLadderPrice, defaultLadderPricePojo);
            result.add(defaultLadderPricePojo);
        }
        serviceResult.setResult(result);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage("查询成功");
        return serviceResult;
    }

    /**
     * 库存阶梯价格配置
     * @param epId 供应商id
     * @param inventoryLadderPriceVo 更新阶梯价格和库存的Vo类
     * @return 返回配置结果
     */
//    @ZookeeperLock
    @Override
    public ServiceResult<Boolean> setLadderPrice(String epId, InventoryLadderPriceVo inventoryLadderPriceVo) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        // 更新库存阶梯价格配置
        for(LadderPriceVo ladderPriceVo : inventoryLadderPriceVo.getInventoryList()){
            int count = serviceHelper.getInventoryMapper().updateLadderPriceIdById(ladderPriceVo.getLadderPriceId(), ladderPriceVo.getId());
            if(count > 0){
                log.info("根据id:[{}]更新阶梯价格id为[{}]成功", ladderPriceVo.getId(), ladderPriceVo.getLadderPriceId());
            }
        }

        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setMessage(ServiceResult.UPDATE_SUCCESS);
        serviceResult.setResult(Boolean.TRUE);
        return serviceResult;
    }

    /**
     * 处理库存阶梯价格数据
     * @param list 库存list数据
     * @return 返回处理结果
     */
    private List<InventoryGetListRespPojo> handleInventoryLadderPriceData(List<InventoryGetListRespPojo> list){
        if(list != null && list.size() > 0){
            for(InventoryGetListRespPojo inventoryGetListRespPojo : list){
                // 最小起订量
                Integer moq = inventoryGetListRespPojo.getMoq();

                // 币种
                Integer currency = inventoryGetListRespPojo.getCurrency();

                // 全部阶梯价格配置
                List<LadderPriceInfoAllRespPojo> allLadderPriceInfoPojoList = new ArrayList<>();

                // 按起订量配置的阶梯价格配置
                List<LadderPriceInfoByMoqPojo> ladderPriceInfoByMoqRespPojoList = new ArrayList<>();

                // 按单价配置的阶梯价格配置
                List<LadderPriceInfoAllRespPojo> ladderPriceInfoByAmountRespPojoList = new ArrayList<>();

                // 查询全部阶梯价格配置数据
                List<LadderPriceInfo> ladderPriceInfos = serviceHelper.getLadderPriceInfoMapper().selectList(new QueryWrapper<>());
                if(ladderPriceInfos != null && ladderPriceInfos.size() > 0){
                    for(LadderPriceInfo ladderPriceInfo : ladderPriceInfos){
                        Integer configType = ladderPriceInfo.getConfigType();

                        // 按起订量配置
                        if(configType == LadderPriceConfigTypeEnum.CONFIG_BY_MOQ.getCode()){
                            QueryWrapper<LadderPriceConfig> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq(LadderPriceConstants.CORRELATION_ID_FIELD, ladderPriceInfo.getId());
                            queryWrapper.orderByAsc(LadderPriceConstants.MQ_FIELD);
                            List<LadderPriceConfig> ladderPriceConfigs = serviceHelper.getLadderPriceConfigMapper().selectList(queryWrapper);
                            if(ladderPriceConfigs != null && ladderPriceConfigs.size() > 0){
                                LadderPriceConfig config = ladderPriceConfigs.get(0);

                                // 库存的最小起订量不为空或最小起订量大于等于阶梯价格配置的最低一级的起订量时添加当前阶梯价格配置
                                if(moq == null || (moq >= config.getMq())){
                                    LadderPriceInfoByMoqPojo ladderPriceInfoByMoqPojo = new LadderPriceInfoByMoqPojo();
                                    LadderPriceInfoAllRespPojo ladderPriceInfoAllRespPojo = new LadderPriceInfoAllRespPojo();

                                    BeanUtils.copyProperties(ladderPriceInfo, ladderPriceInfoAllRespPojo);
                                    BeanUtils.copyProperties(ladderPriceInfo, ladderPriceInfoByMoqPojo);

                                    List<JSONObject> ladderPriceConfigData = new ArrayList<>();
                                    for(LadderPriceConfig ladderPriceConfig : ladderPriceConfigs){
                                        JSONObject json = new JSONObject();
                                        json.put(LadderPriceConstants.MQ_FIELD, ladderPriceConfig.getMq());
                                        json.put(LadderPriceConstants.LOWER_FIELD, ladderPriceConfig.getLower());
                                        BigDecimal unitPrice = serviceHelper.getPriceCalculateHandler().calculateUnitPriceByLower(inventoryGetListRespPojo.getUnitPrice(), ladderPriceConfig.getLower());
                                        if(unitPrice.compareTo(BigDecimal.ZERO) > 0){
                                            json.put(LadderPriceConstants.UNIT_PRICE, unitPrice);
                                        }else{
                                            json.put(LadderPriceConstants.UNIT_PRICE, null);
                                        }
                                        ladderPriceConfigData.add(json);
                                    }

                                    ladderPriceInfoAllRespPojo.setLadderPriceConfigData(ladderPriceConfigData);
                                    allLadderPriceInfoPojoList.add(ladderPriceInfoAllRespPojo);

                                    ladderPriceInfoByMoqPojo.setLadderPriceConfigData(ladderPriceConfigData);
                                    ladderPriceInfoByMoqRespPojoList.add(ladderPriceInfoByMoqPojo);
                                }
                            }
                        }

                        // 按单价配置
                        if(configType == LadderPriceConfigTypeEnum.CONFIG_BY_AMOUNT.getCode()){
                            QueryWrapper<LadderPriceAmountConfig> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq(LadderPriceConstants.LADDER_PRICE_ID_FIELD, ladderPriceInfo.getId());
                            queryWrapper.orderByAsc(LadderPriceConstants.MIN_PRICE_FIELD);
                            List<LadderPriceAmountConfig> ladderPriceAmountConfigs = serviceHelper.getLadderPriceAmountConfigMapper().selectList(queryWrapper);
                            if(ladderPriceAmountConfigs != null && ladderPriceAmountConfigs.size() > 0){
                                LadderPriceInfoAllRespPojo ladderPriceInfoAllRespPojo = new LadderPriceInfoAllRespPojo();
                                BeanUtils.copyProperties(ladderPriceInfo, ladderPriceInfoAllRespPojo);

                                boolean ifReturn = Boolean.FALSE;

                                List<JSONObject> ladderPriceConfigData = new ArrayList<>();
                                for(LadderPriceAmountConfig ladderPriceAmountConfig : ladderPriceAmountConfigs){
                                    QueryWrapper<LadderPriceConfig> queryWrapper1 = new QueryWrapper<>();
                                    queryWrapper1.eq(LadderPriceConstants.CORRELATION_ID_FIELD, ladderPriceAmountConfig.getId());
                                    queryWrapper1.orderByAsc(LadderPriceConstants.MQ_FIELD);
                                    List<LadderPriceConfig> ladderPriceConfigs = serviceHelper.getLadderPriceConfigMapper().selectList(queryWrapper1);
                                    if(ladderPriceConfigs != null && ladderPriceConfigs.size() > 0){
                                        LadderPriceConfig config = ladderPriceConfigs.get(0);
                                        // 库存的最小起订量不为空或最小起订量大于等于阶梯价格配置的最低一级的起订量时添加当前阶梯价格配置
                                        if(moq == null || (moq >= config.getMq())){
                                            ifReturn = Boolean.TRUE;

                                            for(LadderPriceConfig ladderPriceConfig : ladderPriceConfigs){
                                                JSONObject json = new JSONObject();
                                                json.put(LadderPriceConstants.MIN_PRICE, ladderPriceAmountConfig.getMinPrice());
                                                json.put(LadderPriceConstants.MAX_PRICE, ladderPriceAmountConfig.getMaxPrice());
                                                json.put(LadderPriceConstants.MQ_FIELD, ladderPriceConfig.getMq());
                                                json.put(LadderPriceConstants.LOWER_FIELD, ladderPriceConfig.getLower());
                                                BigDecimal unitPrice = serviceHelper.getPriceCalculateHandler().calculateUnitPriceByLower(inventoryGetListRespPojo.getUnitPrice(), ladderPriceConfig.getLower());
                                                if(unitPrice.compareTo(BigDecimal.ZERO) > 0){
                                                    json.put(LadderPriceConstants.UNIT_PRICE, unitPrice);
                                                }else{
                                                    json.put(LadderPriceConstants.UNIT_PRICE, null);
                                                }
                                                ladderPriceConfigData.add(json);
                                            }
                                        }
                                    }
                                }

                                ladderPriceInfoAllRespPojo.setLadderPriceConfigData(ladderPriceConfigData);

                                if(ifReturn){
                                    if(currency == null || currency.intValue() == ladderPriceInfo.getCurrency().intValue()){
                                        ladderPriceInfoByAmountRespPojoList.add(ladderPriceInfoAllRespPojo);
                                    }

                                    allLadderPriceInfoPojoList.add(ladderPriceInfoAllRespPojo);
                                }
                            }
                        }
                    }
                }

                inventoryGetListRespPojo.setAllLadderPriceInfoPojoList(allLadderPriceInfoPojoList);
                inventoryGetListRespPojo.setLadderPriceInfoByMoqRespPojoList(ladderPriceInfoByMoqRespPojoList);
                inventoryGetListRespPojo.setLadderPriceInfoByAmountRespPojoList(ladderPriceInfoByAmountRespPojoList);
            }
        }
        return list;
    }

    /**
     * 更新库存状态，推送mq消息
     * @param id 库存id
     * @param status 要更新的库存状态(0:下架、1:上架)
     */
    private Integer updateInventoryStatusSendMsg(Integer id, Integer status) throws IOException {
        UpdateWrapper<Inventory> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(Constants.ID_FIELD, id);

        Inventory inventory = new Inventory();
        inventory.setStatus(status);

        int update = serviceHelper.getInventoryMapper().update(inventory, updateWrapper);
        if(update > 0){
            log.info("更新库存id:[{}]的状态字段值为[{}]成功", id, status);

            // 推送更新库存状态的mq消息到erp
            sendInventoryUpdateStatusDataToErp(id, status);
            return 1;
        }
        return 0;
    }

    /**
     * 删除阶梯价格配置数据
     * @param epId 供应商id
     */
    private void deleteHistoryLadderPriceData(String epId) {
        QueryWrapper<LadderPriceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, epId);
        serviceHelper.getLadderPriceInfoMapper().delete(queryWrapper);
    }

    /**
     * 删除历史库存数据
     * @param epId 供应商id
     */
    private void deleteHistoryInventoryData(String epId) throws IOException {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ENTERPRISE_ID_FIELD, epId);
        List<Inventory> inventories = serviceHelper.getInventoryMapper().selectList(queryWrapper);
        if(inventories != null && inventories.size() > 0){
            for(Inventory inventory : inventories){
                Integer id = inventory.getId();
                int delete = serviceHelper.getInventoryMapper().deleteById(id);
                if(delete > 0){
                    log.info("id=[{}]的库存数据删除成功", id);

                    // 推送更新库存状态的mq消息到erp
                    sendInventoryUpdateStatusDataToErp(id, InventoryOperateTypeEnum.DELETE.getCode());
                }
            }
        }
    }

    /**
     * 插入库存数据
     * @param inventoryBatchAddVo 库存批量导入接口的Vo类
     * @param authenticationUser  用户信息
     */
    private InventoryAddRespPojo batchAddInsertInventory(InventoryBatchAddVo inventoryBatchAddVo, AuthenticationUser authenticationUser) throws IOException, InterruptedException {
        InventoryAddRespPojo inventoryAddRespPojo = new InventoryAddRespPojo();

        List<InventoryBatchAddParamVo> inventoryList = inventoryBatchAddVo.getInventoryList();
        if(inventoryList != null && inventoryList.size() > 0){
            // 上传成功的数据数量
            int successCount = 0;

            for (InventoryBatchAddParamVo inventoryBatchAddParamVo : inventoryList) {
                // 处理库存批量导入参数的Vo类
                handleInventoryBatchAddParamVo(inventoryBatchAddParamVo);

                // 包装
                String packing = inventoryBatchAddParamVo.getPacking();
                Integer pack = null;
                if(!Strings.isNullOrEmpty(packing)){
                    pack = Integer.valueOf(packing);
                }

                // 币种
                String currency = inventoryBatchAddParamVo.getCurrency();
                Integer currencyInt = null;
                if(!Strings.isNullOrEmpty(currency)){
                    currencyInt = Integer.valueOf(currency);
                }

                String inventoryHome = inventoryBatchAddParamVo.getInventoryHome();
                Integer inventoryHomeInt = null;
                if(!Strings.isNullOrEmpty(inventoryHome)){
                    inventoryHomeInt = Integer.valueOf(inventoryHome);
                }

                Integer sameInventoryId = getSameInventoryId(inventoryBatchAddParamVo.getPartNumber(),inventoryBatchAddParamVo.getBrand(), inventoryBatchAddParamVo.getCount(),
                        inventoryBatchAddParamVo.getPackages(), inventoryBatchAddParamVo.getBatch(), pack, inventoryBatchAddParamVo.getMoq(), inventoryBatchAddParamVo.getMpq(),
                        currencyInt, inventoryBatchAddParamVo.getUnitPrice(), inventoryHomeInt, UnitPriceTypeEnum.SINGLE_PRICE.getCode(), null, authenticationUser.getEpId());
                if(sameInventoryId != null) {
                    successCount++;
                    log.info("品牌:[{}],型号:[{}]的数据在库存中已存在,跳过此条数据处理", inventoryBatchAddParamVo.getBrand(), inventoryBatchAddParamVo.getPartNumber());
                }else{
                    Inventory inventory = new Inventory();
                    BeanUtils.copyProperties(inventoryBatchAddParamVo, inventory);
                    inventory.setCurrency(currencyInt);
                    inventory.setPacking(pack);
                    inventory.setInventoryHome(inventoryHomeInt);
                    inventory.setCreateUser(authenticationUser.getUsername());
                    inventory.setCreateUserId(authenticationUser.getId());
                    inventory.setCreateDate(new Date(System.currentTimeMillis()));
                    inventory.setModifyDate(new Date(System.currentTimeMillis()));
                    inventory.setEnterpriseId(authenticationUser.getEpId());
                    inventory.setStatus(InventoryStatusEnum.SHELVES.getCode());
                    inventory.setUnitPriceType(UnitPriceTypeEnum.SINGLE_PRICE.getCode());
                    inventory.setAdvantageStatus(AdvantageStatusEnum.INVALID.getScStatusCode());
                    inventory.setSource(AdvantageModelSourceEnum.USER_ADD.getCode());
                    int insert = serviceHelper.getInventoryService().insertInventoryData(inventory);

                    // 推送库存新增、修改数据的mq消息到erp
                    if(insert > 0){
                        successCount++;
                        // 推送库存新增数据的mq消息到erp
                        sendInventoryAddEditDataMqMsgToErp(inventory.getId());
                    }
                }
            }

            inventoryAddRespPojo.setAllCount(inventoryList.size());

            // 上传成功的数据数量
            inventoryAddRespPojo.setSuccessCount(successCount);

            // 上传失败的数据数量
            inventoryAddRespPojo.setFailCount(inventoryList.size() - successCount);
        }

        return inventoryAddRespPojo;
    }

    /**
     * 处理库存批量导入参数的Vo类
     * @param inventoryBatchAddParamVo 库存批量导入参数的Vo类
     * @return 返回处理结果
     */
    private InventoryBatchAddParamVo handleInventoryBatchAddParamVo(InventoryBatchAddParamVo inventoryBatchAddParamVo) {
        // 币种
        String currency = inventoryBatchAddParamVo.getCurrency();
        if(!Strings.isNullOrEmpty(currency)){
            currency = currency.replaceAll(" ", "");
            if(ScErpCurrencyEnum.RMB.getDesc().equals(currency)){
                currency = String.valueOf(ScErpCurrencyEnum.RMB.getType());
                inventoryBatchAddParamVo.setCurrency(currency);
            }
            if(ScErpCurrencyEnum.DOLLAR.getDesc().equals(currency)){
                currency = String.valueOf(ScErpCurrencyEnum.DOLLAR.getType());
                inventoryBatchAddParamVo.setCurrency(currency);
            }
        }

        // 包装(1:卷带(TR)、2:Pack)
        String packing = inventoryBatchAddParamVo.getPacking();
        if(!Strings.isNullOrEmpty(packing)){
            packing = packing.replaceAll(" ", "");
            if(PackingEnum.TR.getDesc().equals(packing)){
                packing = String.valueOf(PackingEnum.TR.getType());
                inventoryBatchAddParamVo.setPacking(packing);
            }
            if(PackingEnum.PACK.getDesc().equals(packing)){
                packing = String.valueOf(PackingEnum.PACK.getType());
                inventoryBatchAddParamVo.setPacking(packing);
            }
        }

        // 库存所在地
        String inventoryHome = inventoryBatchAddParamVo.getInventoryHome();
        if(!Strings.isNullOrEmpty(inventoryHome)) {
            inventoryHome = inventoryHome.replaceAll(" ", "");
            if(InventoryHomeEnum.MAINLAND.getDesc().equals(inventoryHome)){
                inventoryBatchAddParamVo.setInventoryHome(String.valueOf(InventoryHomeEnum.MAINLAND.getType()));
            }
            if(InventoryHomeEnum.HONGKONG.getDesc().equals(inventoryHome)){
                inventoryBatchAddParamVo.setInventoryHome(String.valueOf(InventoryHomeEnum.HONGKONG.getType()));
            }
        }

        return inventoryBatchAddParamVo;
    }

    /**
     * 插入库存数据
     * @param inventoryAddParamVo 库存新增参数的Vo类
     * @param authenticationUser 用户信息
     * @return 返回插入结果
     */
    private Map<String, Object> insertInventory(InventoryAddParamVo inventoryAddParamVo, AuthenticationUser authenticationUser) throws InterruptedException {
        Map<String, Object> result = new HashMap<>();

        // 获取同样的库存id
        Integer sameInventoryId = getSameInventoryId(inventoryAddParamVo.getPartNumber(), inventoryAddParamVo.getBrand(), inventoryAddParamVo.getCount(), inventoryAddParamVo.getPackages(),
                inventoryAddParamVo.getBatch(), inventoryAddParamVo.getPacking(), inventoryAddParamVo.getMoq(), inventoryAddParamVo.getMpq(),
                inventoryAddParamVo.getCurrency(), inventoryAddParamVo.getUnitPrice(), inventoryAddParamVo.getInventoryHome(), inventoryAddParamVo.getUnitPriceType(),
                inventoryAddParamVo.getLadderPriceId(), authenticationUser.getEpId());
        if(sameInventoryId != null){
            log.info("品牌:[{}],型号:[{}]的数据在库存中已存在,跳过此条数据处理", inventoryAddParamVo.getBrand(), inventoryAddParamVo.getPartNumber());
            return null;
        }else{
            Inventory inventory = new Inventory();
            BeanUtils.copyProperties(inventoryAddParamVo, inventory);
            inventory.setAdvantageStatus(AdvantageStatusEnum.INVALID.getScStatusCode());
            inventory.setCreateUser(authenticationUser.getUsername());
            inventory.setCreateUserId(authenticationUser.getId());
            inventory.setCreateDate(new Date(System.currentTimeMillis()));
            inventory.setModifyDate(new Date(System.currentTimeMillis()));
            inventory.setEnterpriseId(authenticationUser.getEpId());
            inventory.setStatus(InventoryStatusEnum.SHELVES.getCode());
            inventory.setSource(AdvantageModelSourceEnum.USER_ADD.getCode());
            // 如果未指定单价类型，统一设置为单一价格
            if(inventoryAddParamVo.getUnitPriceType() == null){
                inventory.setUnitPriceType(UnitPriceTypeEnum.SINGLE_PRICE.getCode());
            }

            // 如果当前单价类型为单一价格类型，不保存阶梯价格id数据
            if(inventory.getUnitPriceType().intValue() == UnitPriceTypeEnum.SINGLE_PRICE.getCode().intValue()){
                inventory.setLadderPriceId(null);
            }

            serviceHelper.getInventoryService().insertInventoryData(inventory);
            result.put(Constants.ID, inventory.getId());
        }
        return result;
    }

    /**
     * 处理型号在标准库的匹配数据
     * @param inventory 库存数据
     */
    private void handleBzkData(Inventory inventory) throws InterruptedException {
        // 校验型号、品牌是否在标准库中存在
        JSONArray jsonArray = checkIfHaveInStandardLibrary(inventory.getBrand(), inventory.getPartNumber());

        // 处理标准库匹配数据信息
        if(jsonArray != null && jsonArray.size() > 0){
            for(Object obj : jsonArray){
                JSONObject jsonObject = (JSONObject) obj;
                String matchType = jsonObject.getString(InventoryConstants.MATCH_TYPE);

                // 完全匹配
                if(InventoryConstants.ALL_MATCH.equals(matchType)){
//                    inventory.setBzkBrand(jsonObject.getString(InventoryConstants.BRAND_FIELD));
//                    inventory.setBzkPartNumber(jsonObject.getString(InventoryConstants.PART_NUMBER));
//                    inventory.setBzkMatchStatus(InventoryMatchStatusEnum.MATCHED.getType());
                    break;
                }

                // 推荐匹配
                if(InventoryConstants.RECOMMEND_MATCH.equals(matchType)){
//                    inventory.setBzkMatchStatus(InventoryMatchStatusEnum.UNMATCHED.getType());
//                    inventory.setBzkBrand(jsonArray.toJSONString());
//                    inventory.setBzkPartNumber(jsonArray.toJSONString());
                    break;
                }
            }
        }else{
//            inventory.setBzkMatchStatus(InventoryMatchStatusEnum.UNMATCHED.getType());
        }
    }

    /**
     * 获取同样的库存id
     * @param partNumber 型号
     * @param brand 品牌
     * @param count 数量
     * @param packages 封装
     * @param batch 批次
     * @param pack 包装
     * @param moq 最小起订量
     * @param mpq 最小包装量
     * @param currency 币种
     * @param unitPrice 单价/最低阶梯价
     * @param inventoryHome 库存所在地(1:中国大陆、2:中国香港)
     * @param unitPriceType 价格类型(1:单一价格、2:阶梯价格)
     * @param ladderPriceId 阶梯价格id
     * @param epId 供应商id
     * @return 返回同样的库存id
     */
    private Integer getSameInventoryId(String partNumber, String brand, Integer count, String packages, String batch, Integer pack, Integer moq, Integer mpq,
                                       Integer currency, BigDecimal unitPrice, Integer inventoryHome, Integer unitPriceType, Integer ladderPriceId, String epId){
        Map<String, Object> map = new HashMap<>();
        map.put(InventoryConstants.PART_NUMBER, partNumber);
        map.put(InventoryConstants.BRAND_FIELD, brand);
        map.put(InventoryConstants.COUNT_FIELD, count);
        map.put(InventoryConstants.PACKAGE_FIELD, packages);
        map.put(InventoryConstants.BATCH_FIELD, batch);
        map.put(InventoryConstants.PACKING_FIELD, pack);
        map.put(InventoryConstants.MOQ_FIELD, moq);
        map.put(InventoryConstants.MPQ_FIELD, mpq);
        map.put(InventoryConstants.CURRENCY_FIELD, currency);
        map.put(InventoryConstants.UNIT_PRICE_FIELD, unitPrice);
        map.put(InventoryConstants.INVENTORY_HOME_FIELD, inventoryHome);
        map.put(InventoryConstants.UNIT_PRICE_TYPE_FIELD, unitPriceType);
        map.put(InventoryConstants.LADDER_PRICE_ID_FIELD, ladderPriceId);
        map.put(Constants.ENTERPRISE_ID, epId);
        return serviceHelper.getInventoryMapper().selectIdByParam(map);
    }

    /**
     * 根据阶梯价格id获取阶梯价格配置集合
     * @param ladderPriceId 阶梯价格id
     * @return 返回阶梯价格配置集合
     */
    private List<LadderPriceConfig> getLadderPriceConfigListByLadderPriceId(Integer ladderPriceId, BigDecimal price){
        List<LadderPriceConfig> ladderPriceConfigList = new ArrayList<>();

        // 查询阶梯价格信息
        LadderPriceInfo ladderPriceInfo = serviceHelper.getLadderPriceInfoMapper().selectById(ladderPriceId);
        if(ladderPriceInfo != null) {
            Integer configType = ladderPriceInfo.getConfigType();

            // 按起订量配置
            if (configType == LadderPriceConfigTypeEnum.CONFIG_BY_MOQ.getCode()) {
                ladderPriceConfigList = getLadderPriceConfigListByCorrelationId(ladderPriceId);
            }

            // 按单价配置
            if (configType == LadderPriceConfigTypeEnum.CONFIG_BY_AMOUNT.getCode()) {
                QueryWrapper<LadderPriceAmountConfig> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq(LadderPriceConstants.LADDER_PRICE_ID_FIELD, ladderPriceId);
                List<LadderPriceAmountConfig> list = serviceHelper.getLadderPriceAmountConfigMapper().selectList(queryWrapper);
                Integer amountConfigId = null;

                if (list != null && list.size() > 0) {
                    for (LadderPriceAmountConfig ladderPriceAmountConfig : list) {
                        BigDecimal minPrice = ladderPriceAmountConfig.getMinPrice();
                        BigDecimal maxPrice = ladderPriceAmountConfig.getMaxPrice();

                        if ((minPrice == null && price.compareTo(maxPrice) < 0) || (minPrice !=null && maxPrice != null && price.compareTo(minPrice) > 0 && price.compareTo(maxPrice) <= 0) || (maxPrice == null && price.compareTo(minPrice) > 0)) {
                            amountConfigId = ladderPriceAmountConfig.getId();
                            break;
                        }
                    }

                    ladderPriceConfigList = getLadderPriceConfigListByCorrelationId(amountConfigId);
                }
            }
        }
        return ladderPriceConfigList;
    }

    /**
     * 根据关联id查询阶梯价格配置数据
     * @param correlationId 关联id
     * @return 返回查询结果
     */
    private List<LadderPriceConfig> getLadderPriceConfigListByCorrelationId(Integer correlationId){
        QueryWrapper<LadderPriceConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(LadderPriceConstants.CORRELATION_ID_FIELD, correlationId);
        queryWrapper.orderByAsc(LadderPriceConstants.MQ_FIELD);
        return serviceHelper.getLadderPriceConfigMapper().selectList(queryWrapper);
    }

    /**
     * 推送库存新增、修改数据的mq消息到erp
     * @param inventoryId 库存id
     */
    private void sendInventoryAddEditDataMqMsgToErp(Integer inventoryId) throws IOException {
        Inventory inventory = serviceHelper.getInventoryMapper().selectById(inventoryId);
        if(inventory != null){
            InventorySendMqMsgAddDataPojo inventorySendMqMsgAddDataPojo = new InventorySendMqMsgAddDataPojo();
            BeanUtils.copyProperties(inventory, inventorySendMqMsgAddDataPojo);

            // 处理库存时间字段数据
            handleInventoryTimeData(inventory, inventorySendMqMsgAddDataPojo);

            // 处理阶梯价格数据
            handleLadderPriceData(inventory, inventorySendMqMsgAddDataPojo);

            JSONObject json = (JSONObject) JSONObject.toJSON(inventorySendMqMsgAddDataPojo);

            // 包装发送到rabbitmq的消息内容
            JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_INVENTORY_ADD_EDIT_QUEUE);
            log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_INVENTORY_ADD_EDIT_QUEUE, result.toString());
            serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_INVENTORY_ADD_EDIT_QUEUE, null, result.toString().getBytes());
        }
    }

    /**
     * 推送更新库存状态的mq消息到erp
     * @param id 库存id
     * @param operateType 操作类型(1:上架、2:下架、3:删除)
     */
    private void sendInventoryUpdateStatusDataToErp(Integer id, Integer operateType) throws IOException {
        JSONObject json = new JSONObject();
        json.put(Constants.ID, id);
        json.put(InventoryConstants.OPERATE_TYPE_FIELD, operateType);

        // 包装发送到rabbitmq的消息内容
        JSONObject result = serviceHelper.packageSendRabbitMqMsgData(json, RabbitMqConstants.SC_ERP_INVENTORY_UPDATE_STATUS_DELETE_QUEUE);
        log.info("推送给rabbitmq的交换机:[{}],队列:[{}]的消息内容为:[{}]", RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_INVENTORY_UPDATE_STATUS_DELETE_QUEUE, result.toString());
        serviceHelper.getRabbitMqManager().basicPublish(RabbitMqConstants.SC_ERP_EXCHANGE, RabbitMqConstants.SC_ERP_INVENTORY_UPDATE_STATUS_DELETE_QUEUE, null, result.toString().getBytes());
    }

    /**
     * 处理库存时间字段数据
     * @param inventory 库存数据
     * @param inventorySendMqMsgAddDataPojo 库存批量查询返回的Pojo类
     */
    private void handleInventoryTimeData(Inventory inventory, InventorySendMqMsgAddDataPojo inventorySendMqMsgAddDataPojo) {
        inventorySendMqMsgAddDataPojo.setCreateDate(DateUtils.formatDate(inventory.getCreateDate(), Constants.DATE_PATTERN));
        inventorySendMqMsgAddDataPojo.setModifyDate(DateUtils.formatDate(inventory.getModifyDate(), Constants.DATE_PATTERN));
    }

    /**
     * 处理阶梯价格数据
     * @param inventory 库存数据
     * @param inventorySendMqMsgAddDataPojo 库存批量查询返回的Pojo类
     */
    private void handleLadderPriceData(Inventory inventory, InventorySendMqMsgAddDataPojo inventorySendMqMsgAddDataPojo) {
        Integer unitPriceType = inventory.getUnitPriceType();

        // 起订量集合
        List<Integer> mqList = new ArrayList<>();

        // 单价集合
        List<BigDecimal> unitPriceList = new ArrayList<>();

        // 单一价格
        if(unitPriceType.intValue() == UnitPriceTypeEnum.SINGLE_PRICE.getCode().intValue()){
            if(inventory.getMoq() != null){
                mqList.add(inventory.getMoq());
            }else{
                mqList.add(null);
            }
            if(inventory.getUnitPrice() != null){
                unitPriceList.add(inventory.getUnitPrice());
            }else{
                unitPriceList.add(null);
            }
        }

        // 阶梯价格
        if(unitPriceType.intValue() == UnitPriceTypeEnum.LADDER_PRICE.getCode().intValue()) {
            Integer ladderPriceId = inventory.getLadderPriceId();
            // 获取阶梯价格配置
            if (ladderPriceId != null) {
                List<LadderPriceConfig> ladderPriceConfigList = getLadderPriceConfigListByLadderPriceId(ladderPriceId, inventory.getUnitPrice());
                if (ladderPriceConfigList != null && ladderPriceConfigList.size() > 0) {
                    for (LadderPriceConfig ladderPriceConfig : ladderPriceConfigList) {
                        mqList.add(ladderPriceConfig.getMq());

                        // 根据降比计算降比后的价格
                        BigDecimal unitPrice = serviceHelper.getPriceCalculateHandler().calculateUnitPriceByLower(inventory.getUnitPrice(), ladderPriceConfig.getLower());
                        unitPriceList.add(unitPrice);
                    }
                }
            }
        }

        inventorySendMqMsgAddDataPojo.setMqList(mqList);
        inventorySendMqMsgAddDataPojo.setUnitPriceList(unitPriceList);
    }

    /**
     * 删除库存信息，推送mq消息
     * @param id 库存id
     * @return 返回删除数据数量
     */
    private int deleteInventorySendMqMsg(Integer id) throws IOException {
        QueryWrapper<Inventory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.ID_FIELD, id);
        int delete = serviceHelper.getInventoryMapper().delete(queryWrapper);
        if(delete > 0){
            log.info("id=[{}]的库存数据删除成功", id);
            // 推送更新库存状态的mq消息到erp
            sendInventoryUpdateStatusDataToErp(id, InventoryOperateTypeEnum.DELETE.getCode());
        }
        return delete;
    }

    /**
     * 获取符合条件的库存id集合
     * @param brand 品牌
     * @param partNumber 型号
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param status 状态(0:已下架、1:已上架)
     * @param inventoryHome 库存所在地(1:中国大陆、2:中国香港)
     * @param unitPriceType 价格类型(1:单一价格、2:阶梯价格)
     * @param ladderPriceId 阶梯价格id
     * @param epId 供应商id
     * @return 返回查询结果
     */
    private List<Integer> getMatchConditionIdList(String brand, String partNumber, String startDate, String endDate,
                                                  Integer status, Integer inventoryHome, Integer unitPriceType, Integer ladderPriceId, String epId){
        Map<String, Object> map = new HashMap<>();
        map.put(InventoryConstants.BRAND_FIELD, brand);
        map.put(InventoryConstants.PART_NUMBER, partNumber);
        map.put(InventoryConstants.START_DATE, startDate);
        map.put(InventoryConstants.END_DATE, endDate);
        map.put(InventoryConstants.STATUS_FIELD, status);
        map.put(InventoryConstants.INVENTORY_HOME, inventoryHome);
        map.put(InventoryConstants.UNIT_PRICE_TYPE, unitPriceType);
        map.put(InventoryConstants.LADDER_PRICE_ID, ladderPriceId);
        map.put(InventoryConstants.ENTERPRISE_ID, epId);

        // 根据参数查询需要删除的id集合
        return serviceHelper.getInventoryMapper().selectDeleteDataIdsByParam(map);
    }

    /**
     * 根据库存id获取型号数据map
     * @param id 库存id
     * @return 返回Map数据
     */
    private Map<String, String> getModelMapByInventoryId(Integer id){
        Inventory inventory = serviceHelper.getInventoryMapper().selectById(id);
        Map<String, String> map = new HashMap<>();
        map.put(AdvantageModelConstants.BRAND_FIELD, inventory.getBrand());
        map.put(AdvantageModelConstants.PART_NUMBER, inventory.getPartNumber());
        return map;
    }

    /**
     * 校验型号、品牌是否在标准库中存在
     * @param brand 品牌
     * @param partNumber 型号
     * @return 返回校验结果
     */
    private JSONArray checkIfHaveInStandardLibrary(String brand, String partNumber) throws InterruptedException {
        JSONArray result = null;

        // 使用智能bom接口获取标准库数据
        //result = useBomGetStandardLibraryData(brand, partNumber);

        // 根据型号、品牌获取标准库数据
        result = getStandardLibraryDataByBrandPartNumber(brand, partNumber);

        return result;
    }

    /**
     * 根据型号、品牌获取标准库数据
     * @param brand 品牌
     * @param partNumber 型号
     * @return 返回查询结果
     */
    private JSONArray getStandardLibraryDataByBrandPartNumber(String brand, String partNumber) {
        JSONArray result = new JSONArray();

        List<ProductInfoPojo> productInfoPojos = serviceHelper.getProductsService().selectProduceInfoByBrandPartNumber(brand, partNumber);
        if(productInfoPojos != null && productInfoPojos.size() > 0){
            for(ProductInfoPojo productInfoPojo : productInfoPojos){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put(InventoryConstants.BRAND_FIELD, productInfoPojo.getBrand());
                jsonObject.put(InventoryConstants.PART_NUMBER, productInfoPojo.getPartNumber());
                jsonObject.put(InventoryConstants.MATCH_TYPE, InventoryConstants.ALL_MATCH);
                result.add(jsonObject);
            }
        }
        return result;
    }

    /**
     * 使用智能bom接口获取标准库数据
     * @param brand 品牌
     * @param partNumber 型号
     * @return 返回查询结果
     */
    private JSONArray useBomGetStandardLibraryData(String brand, String partNumber) throws InterruptedException {
        JSONArray result = null;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(DyjConstants.REQUEST_SERVICE, DyjConstants.ES_BOM_B1B);
        jsonObject.put(DyjConstants.REQUEST_ITEM, DyjConstants.SEARCH);
        jsonObject.put(DyjConstants.TOKEN, serviceHelper.getDyjInterfaceAddressConfig().getToken());

        JSONObject data = new JSONObject();
        data.put(DyjConstants.QUERY, partNumber);
        jsonObject.put(DyjConstants.DATA, data);

        String str = null;
        try {
            Thread.sleep(10);
            str = HttpUtils.sendPost(serviceHelper.getDyjInterfaceAddressConfig().getBom(), jsonObject.toString());
        }catch (Exception e){
            log.info("型号:[{}]在智能BOM接口中第一次查询未获取到结果,休眠100毫秒后再次查询", partNumber);
            Thread.sleep(100);
            try {
                str = HttpUtils.sendPost(serviceHelper.getDyjInterfaceAddressConfig().getBom(), jsonObject.toString());
            }catch (Exception e1){
                log.info("型号:[{}]在智能BOM接口中第二次查询未获取到结果,休眠100毫秒后再次查询", partNumber);
                Thread.sleep(100);
                try {
                    str = HttpUtils.sendPost(serviceHelper.getDyjInterfaceAddressConfig().getBom(), jsonObject.toString());
                }catch (Exception e2){
                    log.info("型号:[{}]在智能BOM接口中已查询三次未获取结果,结束查询,视为型号不存在", partNumber);
                }
            }
        }

        if(!Strings.isNullOrEmpty(str)){
            try {
                JSONObject json = (JSONObject) JSONObject.parse(str);
                if(json != null && !json.isEmpty()){
                    Integer statusCode = json.getInteger(DyjConstants.STATUS_CODE);
                    if(statusCode == 200){
                        JSONObject jsonJSONObject = json.getJSONObject(DyjConstants.DATA);
                        if(jsonJSONObject != null && !jsonJSONObject.isEmpty()){
                            JSONArray jsonArray = jsonJSONObject.getJSONArray(DyjConstants.DATA_LOWER);
                            if(jsonArray != null && jsonArray.size() > 0){
                                for(Object obj : jsonArray){
                                    JSONObject object = (JSONObject) obj;
                                    String manufacturer = object.getString(InventoryConstants.MANUFACTURER);
                                    String modelNumber = object.getString(InventoryConstants.MODEL_NUMBER);
                                    if(!Strings.isNullOrEmpty(manufacturer) && !Strings.isNullOrEmpty(modelNumber) && brand.equals(manufacturer) && partNumber.equals(modelNumber)){
                                        continue;
                                    }else{
                                        result = new JSONArray();
                                        JSONObject jsonObject1 = new JSONObject();
                                        jsonObject1.put(InventoryConstants.BRAND_FIELD, manufacturer);
                                        jsonObject1.put(InventoryConstants.PART_NUMBER, modelNumber);
                                        jsonObject1.put(InventoryConstants.MATCH_TYPE, object.getString(InventoryConstants.MATCH_TYPE_CN));
                                        result.add(jsonObject1);
                                    }
                                }
                            }
                        }
                    }
                }
            }catch (Exception e){
                log.info("型号:[{}]在智能BOM接口查询出现异常,接口返回信息为[{}]", partNumber, str);
            }
        }

        return result;
    }

    /**
     * 将库存列表查询结果数据添加到redis中
     * @param key redis的key
     * @param data 数据
     */
    private void addInventoryQueryResultDataToRedis(String key, List<InventoryBatchQueryPojo> data){
        if(data != null && data.size() > 0){
            for(InventoryBatchQueryPojo inventoryBatchQueryPojo : data){
                String scoreStr = "-" + inventoryBatchQueryPojo.getCreateDate().getTime() + "" + inventoryBatchQueryPojo.getStatus() + inventoryBatchQueryPojo.getId();
                String value = JSONObject.toJSONString(inventoryBatchQueryPojo);
                serviceHelper.getRedisManager().zAdd(key, value, Double.parseDouble(scoreStr));
            }
        }
    }

    /**
     * 根据条件从redis中获取数据
     * @param status 状态
     * @param inventoryHome 库存所在地
     * @param unitPriceType 价格类型
     * @param ladderPriceId 阶梯价格id
     * @param enterpriseId 供应商id
     * @return 返回查询结果
     */
    private Set<String> getInventoryDataListFromRedis(String status, String inventoryHome, Integer unitPriceType, Integer ladderPriceId, String enterpriseId){
        // 根据参数获取库存在redis中的key
        String key = getInventoryRedisKeyByParam(status, inventoryHome, unitPriceType, ladderPriceId, enterpriseId);
        return serviceHelper.getRedisManager().zRange(key, 0, -1);
    }

    /**
     * 根据参数获取库存在redis中的key
     * @param status 状态
     * @param inventoryHome 库存所在地
     * @param unitPriceType 价格类型
     * @param ladderPriceId 阶梯价格id
     * @param enterpriseId 供应商id
     * @return 返回redis中的key
     */
    private String getInventoryRedisKeyByParam(String status, String inventoryHome, Integer unitPriceType, Integer ladderPriceId, String enterpriseId){
        StringBuilder key = new StringBuilder();
        key.append(RedisKeyPrefixEnum.INVENTORY_QUERY.getCode());
        // 状态
        if(!Strings.isNullOrEmpty(status)){
            key.append("_S").append(status);
        }

        // 库存所在地
        if(!Strings.isNullOrEmpty(inventoryHome)){
            key.append("_I").append(inventoryHome);
        }

        // 价格类型
        if(unitPriceType != null){
            key.append("_U").append(unitPriceType);
        }

        // 阶梯价格id
        if(ladderPriceId != null){
            key.append("_L").append(ladderPriceId);
        }

        // 供应商id
        if(enterpriseId != null){
            key.append("_E").append(enterpriseId);
        }
        return key.toString();
    }

    /**
     * 从redis中获取库存数据
     * @param idList 主键集合
     * @return 返回查询结果
     */
    private List<InventoryGetListRespPojo> getInventoryListFromRedis(List<Integer> idList){
        List<InventoryGetListRespPojo> result = new ArrayList<>();

        List<String> param = new ArrayList<>();
        for(Integer id : idList){
            String redisKey =  RedisKeyPrefixEnum.INVENTORY_DATA.getCode() + "_" + id;
            param.add(redisKey);
        }

        List<String> list = serviceHelper.getRedisManager().getList(param);
        if(list != null && list.size() > 0){
            for(String redisStr : list){
                if(!Strings.isNullOrEmpty(redisStr)){
                    InventoryGetListRespPojo inventoryGetListRespPojo = JSONObject.parseObject(redisStr, InventoryGetListRespPojo.class);
                    result.add(inventoryGetListRespPojo);
                }
            }
        }

        return result;
    }

    /**
     * 添加特殊情况的数据
     * @param allSituation 库存所有情况的pojo类
     * @param epIdList 供应商id集合
     */
    private void addSpecialInventoryAllSituationPojoData(List<InventoryAllSituationPojo> allSituation, List<String> epIdList){
        if(epIdList != null && epIdList.size() > 0){
            for(String epId : epIdList){
                InventoryAllSituationPojo inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setStatus(InventoryStatusEnum.SHELVES.getCode());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setStatus(InventoryStatusEnum.NO_SHELVES.getCode());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setInventoryHome(InventoryHomeEnum.MAINLAND.getType());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setInventoryHome(InventoryHomeEnum.HONGKONG.getType());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setUnitPriceType(UnitPriceTypeEnum.SINGLE_PRICE.getCode());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setUnitPriceType(UnitPriceTypeEnum.LADDER_PRICE.getCode());
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);

                // 查询当前供应商使用的阶梯价格id
                List<Integer> list = serviceHelper.getInventoryMapper().selectLadderPriceIdsByEpId(epId);
                if(list != null && list.size() > 0){
                    for(Integer ladderPriceId : list){
                        inventoryAllSituationPojo = new InventoryAllSituationPojo();
                        inventoryAllSituationPojo.setLadderPriceId(ladderPriceId);
                        inventoryAllSituationPojo.setEnterpriseId(epId);
                        allSituation.add(inventoryAllSituationPojo);
                    }
                }

                inventoryAllSituationPojo = new InventoryAllSituationPojo();
                inventoryAllSituationPojo.setEnterpriseId(epId);
                allSituation.add(inventoryAllSituationPojo);
            }
        }
    }

    /**
     * 判断是否为优势品牌、型号，补充字段
     * @param data 数据
     */
    private void judgeIfAdvantageBrandModel(List<InventoryBatchQueryPojo> data){
        if(data != null && data.size() > 0){
            for(InventoryBatchQueryPojo inventoryBatchQueryPojo : data){
                // 判断是否为优势品牌
                Integer ifAdvantageBrand = inventoryBatchQueryPojo.getIfAdvantageBrand();
                if(ifAdvantageBrand != null && ifAdvantageBrand > 0){
                    inventoryBatchQueryPojo.setIfAdvantageBrand(AdvantageStatusEnum.EFFECTIVE.getScStatusCode());
                }

                // 根据品牌、型号查询优势型号数据
                String advantageModelKey = RedisKeyPrefixEnum.ADVANTAGE_MODEL_DATA.getCode() + "_" + inventoryBatchQueryPojo.getPartNumber() + "_" + inventoryBatchQueryPojo.getBrand() + "_" + inventoryBatchQueryPojo.getEnterpriseId();
                String advantageModelData = (String) serviceHelper.getRedisManager().get(advantageModelKey);
                if(!Strings.isNullOrEmpty(advantageModelData)){
                    JSONObject json = (JSONObject) JSONObject.parse(advantageModelData);
                    if(json != null && !json.isEmpty()){
                        Integer auditStatus = json.getInteger(InventoryConstants.AUDIT_STATUS);
                        Integer advantageStatus = json.getInteger(InventoryConstants.ADVANTAGE_STATUS);
                        if(auditStatus != null && advantageStatus != null && auditStatus.intValue() == AuditStatusEnum.APPROVE.getScStatusCode() && advantageStatus.intValue() == AdvantageStatusEnum.EFFECTIVE.getScStatusCode()){
                            inventoryBatchQueryPojo.setIfAdvantageModel(AdvantageStatusEnum.EFFECTIVE.getScStatusCode());
                        }else{
                            inventoryBatchQueryPojo.setIfAdvantageModel(AdvantageStatusEnum.INVALID.getScStatusCode());
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据请求参数筛选数据
     * @param redisList redis数据
     * @param inventoryQueryVo 库存信息列表查询接口的Vo类
     * @return 返回处理后的数据
     */
    private List<InventoryBatchQueryPojo> screenRedisList(List<InventoryBatchQueryPojo> redisList, InventoryQueryVo inventoryQueryVo) throws ParseException {
        List<InventoryBatchQueryPojo> result = new ArrayList<>();

        if(redisList != null && redisList.size() > 0){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            // 型号
            String partNumber = inventoryQueryVo.getPartNumber();
            Pattern partNumberPattern = null;
            if(!Strings.isNullOrEmpty(partNumber)){
                partNumberPattern = Pattern.compile(partNumber, Pattern.CASE_INSENSITIVE);
            }

            // 品牌
            String brand = inventoryQueryVo.getBrand();
            Pattern brandPattern = null;
            if(!Strings.isNullOrEmpty(brand)){
                brandPattern = Pattern.compile(brand, Pattern.CASE_INSENSITIVE);
            }

            // 开始时间
            String startDateStr = inventoryQueryVo.getStartDate();
            Date startDate = null;
            if(!Strings.isNullOrEmpty(startDateStr)){
                startDate = sdf.parse(startDateStr);
            }

            // 结束时间
            String endDateStr = inventoryQueryVo.getEndDate();
            Date endDate = null;
            if(!Strings.isNullOrEmpty(endDateStr)){
                endDate = sdf.parse(endDateStr);
            }

            for(InventoryBatchQueryPojo inventoryBatchQueryPojo : redisList){
                // 匹配型号
                if(!Strings.isNullOrEmpty(partNumber) && !Strings.isNullOrEmpty(inventoryBatchQueryPojo.getPartNumber())){
                    Matcher contentMatcherContent = partNumberPattern.matcher(inventoryBatchQueryPojo.getPartNumber());
                    boolean b = contentMatcherContent.find();
                    if(!b){
                        continue;
                    }
                }

                // 匹配品牌
                if(!Strings.isNullOrEmpty(brand) && !Strings.isNullOrEmpty(inventoryBatchQueryPojo.getBrand())){
                    Matcher contentMatcherContent = brandPattern.matcher(inventoryBatchQueryPojo.getBrand());
                    boolean b = contentMatcherContent.find();
                    if(!b){
                        continue;
                    }
                }

                // 开始时间
                if(startDate != null && inventoryBatchQueryPojo.getCreateDate() != null && inventoryBatchQueryPojo.getCreateDate().getTime() < startDate.getTime()){
                    continue;
                }

                // 结束时间
                if(endDate != null && inventoryBatchQueryPojo.getCreateDate() != null && inventoryBatchQueryPojo.getCreateDate().getTime() > endDate.getTime()){
                    continue;
                }

                result.add(inventoryBatchQueryPojo);
            }
        }

        return result;
    }
}